package countServers;

public class Solution {
    public int countServers(int[][] grid) {
        // 遍历所有单元格 判断与它同一列和同一行有没有通信其
//        int ans = 0;
//        for (int i = 0; i < grid.length; i++) {
//            for (int j = 0; j < grid[i].length; j++) {
//                if(grid[i][j] == 1) {
//                    if(check(i,j,grid))ans++;
//                }
//            }
//        }
//        return ans;
        int m = grid.length;
        int n = grid[0].length;
        int[] cols = new int[n];
        int[] rows = new int[m];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                rows[i] += grid[i][j];
                cols[j] += grid[i][j];
            }
        }
        int ans = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if(grid[i][j] == 1 && (cols[j] > 1 ||rows[i] > 1)) {
                    ans++;
                }
            }
        }
        return ans;
    }
//    private boolean check(int i,int j,int[][] grid) {
//        for (int col = 0; col < grid.length; col++) {
//            if(col!=j&&grid[i][col] == 1) {
//                return true;
//            }
//        }
//        for (int row = 0; row < grid.length; row++) {
//            if(row!=i&&grid[row][j] == 1) {
//                return true;
//            }
//        }
//        return false;
//    }
    
}
